<?php

namespace app\admin\controller;

use controller\BasicAdmin;
use service\DataService;
use service\ToolsService;
use think\Db;
use think\exception\HttpResponseException;

/**
 * 代理商级别管理
 */
class AgentLevel extends BasicAdmin
{
    
    public $agent_level= 'jixie_agent_level';

    /**
     * 分类列表
     * @return array|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function lists()
    {
        $this->title = '分类';
        $db = Db::name($this->agent_level)->where(['is_deleted' => '0']);
        return parent::_list($db->order('sort desc,level_id desc'), 'level_id', false);
    }

    /**
     * 添加
     * @return array|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add()
    {
        return $this->_form($this->agent_level, 'form');
    }

    /**
     * 编辑
     * @return array|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit()
    {
        if (!$this->request->isPost()) {
            $level_id = $this->request->get('id');
            $data = Db::name($this->agent_level)->where(['level_id' => $level_id, 'is_deleted' => '0'])->find();
            empty($data) && $this->error('需要编辑的级别不存在！');
            return $this->fetch('form', ['vo' => $data, 'title' => '编辑']);
        }
        try {
            $level_id = $this->request->post('id');
            $post = $this->request->post();
            $data = Db::name($this->agent_level)->where(['level_id' => $level_id, 'is_deleted' => '0'])->find();
            empty($data) && $this->error('编辑失败，请稍候再试！');

            Db::transaction(function () use ($post, $level_id, $data) {
                $where = ['level_id' => $level_id];
                Db::name($this->agent_level)->where($where)->update($post);

            });

        } catch (HttpResponseException $exception) {
            return $exception->getResponse();
        } catch (\Exception $e) {
            $this->error('编辑失败，请稍候再试！' . $e->getMessage());
        }
        $this->success('编辑成功！', "");
    }

    /**
     * 删除
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function del()
    {
        if (DataService::update($this->agent_level)) {
            $this->success("删除成功！", '');
        }
        $this->error("删除失败，请稍候再试！");
    }

}
